package org.nerve.android.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;

/**
 * @项目名称 :nerveAndroid
 * @文件名称 :NerveAnnotation.java
 * @所在包 :org.nerve.android.annotation
 * @功能描述 :
 *	解析activity相关的注解类
 * @创建者 :集成显卡	1053214511@qq.com
 * @公司：IBM GDC (http://www.ibm.com/)
 * @创建日期 :2013-6-15
 * @修改记录 :
 */
public class NerveAnnotation {

	/**
	 * 解析Class层的注解
	 */
	public static void parseActivityClass(Activity owner){
		org.nerve.android.annotation.Acvitity activity = owner.getClass()
				.getAnnotation(org.nerve.android.annotation.Acvitity.class);
		if(activity != null){
			System.out.println("layout to：" + activity.layout());
			owner.setContentView(activity.layout());
		}
		
	}
	
	public static void parseActivity(Activity owner){
		parseActivityClass(owner);
		
		Field[] fields = owner.getClass().getDeclaredFields();
		String name = null;
		for(Field field:fields){
			ViewOnId voi = field.getAnnotation(ViewOnId.class);
			if(voi != null){
				try{
					if(!field.isAccessible()){
						field.setAccessible(true);
					}
					
					//优先检查id
					if(voi.id() > 0){
						//设置了父视图，那么会从这个parent中调用 findViewById
						if(voi.parent().length() > 0){
							Field parent = owner.getClass().getDeclaredField(voi.parent());
							parent.setAccessible(true);
							
							if(parent.get(owner) != null){
								View parentV = (View)parent.get(owner);
								field.set(owner, field.getType().cast(parentV.findViewById(voi.id())));
							}
						}else{
							field.set(owner, field.getType().cast(owner.findViewById(voi.id())));
						}
					}
					//再判断是否指定了layout
					else if(voi.layout() > 0){
						field.set(owner, field.getType().cast(View.inflate(owner, voi.layout(), null)));
					}
					//如果id 跟layout 都没有配置，这个view的绑定取消
					else{
						continue;
					}
					name = voi.clickListener();
					if(name.length() > 0){
						Method method = field.getType().getMethod("setOnClickListener", OnClickListener.class);
						if(voi.clickListener().equals("this")){
							method.invoke(field.get(owner), owner);
						}else{
							Field listener = owner.getClass().getDeclaredField(voi.clickListener());
							listener.setAccessible(true);
							if(listener.getClass().equals(OnClickListener.class)){
								method.invoke(field.get(owner), listener.get(owner));
							}
						}
					}
					
					System.out.println(field.getName() + " init ok.id=" + voi.id() +", clickListener=" + voi.clickListener());
				}catch(Exception e){
					System.err.println("error on bind view '" + field.getName() +"':" + e.getMessage());
					e.printStackTrace(System.out);
				}
			}
		}
	}
}
